<?php
/**
 * 按模板导出数据excel
 * User：liujun
 * Date：2022/3/7
 * Time：8:37 PM
 */

namespace Encore\Admin\Grid\Exporters;

use Maatwebsite\Excel\Concerns\WithMapping;

class AdminExporter extends ExcelExporter implements WithMapping
{
    protected $fileName = '导出文件.xlsx';
    /**
     * 表名
     * @var string
     */
    protected string $tableName;

    /**
     * 需要重写显示的数据
     * @var array
     */
    protected array $rewrites;


    /**
     * 导出字段
     * @param array $columns
     * @return AdminExporter
     */
    public function withColumns(array $columns): static
    {
        $this->columns = $columns;
        return $this;
    }

    /**
     * 通过文件配置预导出字段
     * @param string $path
     * @return $this
     */
    public function withFileColumns(string $path): static
    {
        $this->columns = include($path);
        return $this;
    }

    /**
     * 设置导出数据名称
     * @param string $fileName
     * @return AdminExporter
     */
    public function withFileName(string $fileName): static
    {
        $this->fileName = $fileName . '.xlsx';
        return $this;
    }


    /**
     * @param $row
     * @return array
     * @throws \Throwable
     */
    public function map($row): array
    {
        $map = [];
        foreach ($this->columns as $key => $name) {
            $map[$key] = $this->rewrite($key, data_get($row, $key));
        }
        return $map;
    }

    /**
     * set rewrites data
     * @param array $rewrites
     * @return AdminExporter
     */
    public function withRewrites(array $rewrites): AdminExporter
    {
        $this->rewrites = $rewrites;
        return $this;
    }

    /**
     * 重写字段
     * @param $key
     * @param $val
     * @return string|null
     */
    public function rewrite($key, $val): ?string
    {
        if (array_key_exists($key, $this->rewrites)) {
            return data_get($this->rewrites, $key . '.' . $val);
        }
        return is_numeric($val) ? $val : ($val . ' ');
    }
}